package cn.codexin.wechatofficial.wechat;

import cn.codexin.wechatofficial.dto.AccessTokenDTO;
import cn.codexin.wechatofficial.dto.UserInfoAccessTokenDTO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.tomcat.util.buf.HexUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created by xinGao 2020/4/22
 */
@Component
public class WeChatProvider {

    @Value("${wechat.grant-type}")
    private String grant_type;

    @Value("${wechat.app-id}")
    private String appId;

    @Value("${wechat.app-secret}")
    private String secret;

    @Value("${wechat.token}")
    private String token;

    @Value("${wechat.server-url}")
    private String serverUrl;

//    public List<String>getOpenidList(String accessToken){
////        String accessToken = "37_R6g70_TcYA3wHTCPVw9ZEP7Z62L119xmAEfZiFqOQ0rtt2wKXNmaNKW3UJdS98OQR4iWiPpGrkKuw_7iJ5_dE_CbYABG60C34QDS4zVMEqi6ciu858g8EjxX5BgYOn4XPm40aVSdi-sZMZQjEEMeABAKKS";
//        OkHttpClient client = new OkHttpClient();
//        Request request = new Request.Builder()
//                .url("https://api.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken).build();
//        try (Response response = client.newCall(request).execute()) {
//            //错误情况还未处理
//            JSONObject data = JSON.parseObject(JSON.parseObject(Objects.requireNonNull(response.body()).string()).getString("data"));
//            JSONArray openidJSONArray = data.getJSONArray("openid");
//            List<String> openidList = new ArrayList<>();
//            if (openidJSONArray != null && openidJSONArray.size() > 0) {
//                for (int i = 0; i < openidJSONArray.size(); i++) {
//                    String openid = openidJSONArray.getString(i);
//                    openidList.add(openid);
//                }
//            }
//            return openidList;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    public AccessTokenDTO getAccessToken(){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+ appId +"&secret="+secret).build();
        try (Response response = client.newCall(request).execute()) {
            //错误情况还未处理
            return JSON.parseObject(response.body().string(), AccessTokenDTO.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public UserInfoAccessTokenDTO getUserInfoAccessToken(String code){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+secret+"&code="+code+"&grant_type=authorization_code").build();
        try (Response response = client.newCall(request).execute()) {
            //错误情况还未处理
            return JSON.parseObject(response.body().string(), UserInfoAccessTokenDTO.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

//    public UserInfoDTO getUserInfo(String openid,String access_token){
//        OkHttpClient client = new OkHttpClient();
//        Request request = new Request.Builder()
//                .url("https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN").build();
//        try (Response response = client.newCall(request).execute()) {
//            //错误情况还未处理
//            return JSON.parseObject(response.body().string(), UserInfoDTO.class);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    public boolean checkSignature(String signature, String timestamp, String nonce){
        //首先解密微信服务器发过来的请求，确认该请求有效
        try {
            Objects.requireNonNull(signature);
            Objects.requireNonNull(timestamp);
            Objects.requireNonNull(nonce);
        }catch (NullPointerException e){
            return false;
        }
        String[] array = new String[]{token, timestamp, nonce};
        List<String> list = new ArrayList<>(Arrays.asList(array));
        //默认字典排序
        String str = list.stream().sorted().collect(Collectors.joining());
        //Sha1 加密
        MessageDigest sha1 = null;
        try {
            sha1 = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] digest = sha1.digest(str.getBytes());
        String realMessage = HexUtils.toHexString(digest);
        if(realMessage.equals(signature)){
            return true;
        }
        else return false;
    }
}
